class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            name: '',
            namber: '',
            list: [],
            ishide: 'none',
            counts: [],
            start: 0,
            pagesize: 12,
            keyword: '',
            showswitch: !0,
            pagestart: 0,
            clicknew: !1,
            id: 0,
            isshow: 1,
            imgsrc: "",
            fileimgshow: !0,
        };
    }

    formatlist(list) {
        var listitem = [],wulist=[];
        if(list.length>0){
            list.forEach((x, i) => {
                listitem.push(
                    <tr key={i}>
                         <td><p className="td-img" style={{display:x.thumbpath&&x.thumbpath!='null'?'':'none'}}><img src={x.thumbpath?`${API_HEAD}imgs/${x.thumbpath}`:''}/></p><p style={{display:x.thumbpath&&x.thumbpath!='null'?'none':''}}>无</p></td>
                        <td>{x.name}</td>
                        <td className="tconter">{x.isshow == "1" ? "显示" : "隐藏"}</td>
                        <td className="tconter">{x.orders}</td>
                        <td className="operatebox">
                            <div className='operate' id={"ope" + x.id}>
                                <div data-toggle="modal" data-target="#modalOne">
                                    <img src="./src/edit.png" />
                                    <p className='edit' onClick={this.todetail.bind(this, x.id)}>编辑</p>
                                </div>
                                <div>
                                    <img src={`./src/${x.state == "1" ? "hide" : "show"}.png`} />
                                    <p className='edit' onClick={this.setshow.bind(this, x.id, x.isshow)}>{x.state == "0" ? "隐藏" : "显示"}</p>
                                </div>
                                <div>
                                    <img src="./src/del.png" />
                                    <p className='edit colred' onClick={this.del.bind(this, x.id)}>删除</p>
                                </div>
                            </div>
                        </td>
                    </tr>
    
    
                )
            });
        } else {
            wulist.push(
                <p className="wulist">暂无数据</p>
            )
        }
        this.setState({ listitem, list, originallist: list,wulist })
    }
    // 编辑
    todetail(e) {
        var { list,imgsrc } = this.state,item=[];
        list.forEach(x => {
            if (x.id == e) {
                if(x.thumbpath&&x.thumbpath!='null'){
                    imgsrc=`${API_HEAD}imgs/${x.thumbpath}`
                    this.setState({imgsrc,fileimgshow:!1})
                }
                this.setState({ id: e, name: x.name,namber:x.orders })
            }
        });
    }
    // 显示隐藏
    setshow(e, i) {
        let { start } = this.state
        audiocatesetshow(e, res => {
            if (res.issuccess == 1) {
                alert(`${i == "1" ? '隐藏' : '显示'}成功`)
                this.freshlist(start)
            }
        })

    }

    // 删除
    del(e) {
        this.setState({ delid: e }, () => {
            $('#myModal').modal('toggle');
        })
    }
    confirmdel() {
        let { delid, start } = this.state
        audiocatedel(delid, res => {
            if (res.issuccess == 1) {
                alert('删除成功')
                $('#myModal').modal('toggle');
                this.freshlist(start)
            }
        })
    }

    inputchange(prop, e) {
        this.setState({ [prop]:e.target.value }) 
    }
    // 点击新建或编辑
    // getnew(start) {
    //     this.setState({ clicknew: !this.state.clicknew, id: '0' });
    // }

    submit() {
        var {  name, namber,imgsrc,start } = this.state, that = this, err = '',imgarr = [];
        console.log(namber, 'namber')
        var reg = /^[0-9]{1,3}$/
        if (!reg.test(namber)) {
            err = "请输入整数"
        }
        if (namber > 100 || namber < 0 || namber == "") err = "请输入0-100的数字"

        if (name == "") err = "请输入姓名"
        if (err.length > 0) {
            alert(err);
            return
        }
        if(!imgsrc){
            var submitdata = { name, orders: namber,thumbpath:imgsrc }
    
            if (this.state.id > 0) submitdata['id'] = this.state.id;
            audiocateaoe(submitdata, res => {
                if (res.issuccess == 1) {
                    alert(`${this.state.id > 0 ? '修改' : '保存'}成功`);
                    that.setState({name:'',imgsrc:'',fileimgshow:!0,id:0,orders:''})
                    that.freshlist(start)
                }
            })

        }else{
            imgarr.push(imgsrc)
            that.uploadimg(imgarr)
        }

    }
    searchinput(e) {
        // console.log(e.target.value,'e.target.value')
        this.setState({ keyword: e.target.value })
    }
    // 排序
    // search(){
    //     if(this.state.keyword.length==0) return;
    //     let {keyword} = this.state;

    // audiocatesetorder(keyword,res=>{
    //     if(res.issuccess==1){
    //         // console.log(res,'res.data')
    //         this.formatlist(res.data);
    //         this.setState({showswitch:!1})
    //     }
    // })

    // }
    reset() {
        this.setState({ keyword: '', showswitch: !0 });
        this.freshlist(0, 'ALL');
    }
    inputchangeall() {

    }
    componentDidMount() {
        this.freshlist(0)

    }

    
    freshlist(start) {
        let { pagesize } = this.state;
        audiocatebkgetlist({ pagesize, start }, res => {
            if (res.issuccess == 1) {
                if (start == 0) {
                    let pagecount = Math.ceil(res.total / pagesize);
                    this.setpager(pagecount, start);
                    this.setState({ start,total:res.total })
                }
                this.formatlist(res.list);
            }
        })
    }
//  setpager(pagecount, start) {
//         let counts = [];
//         for (let i = 1; i < pagecount + 1; i++) {
//             counts.push(start + i)
//         }
//         this.setState({ counts, pagestart: 0 })
//     }
//     clickpage(e) {
//         let { start, pagesize,state } = this.state
//         start = e * pagesize
//         $("input[name='checkbox']").prop("checked",false);
//         this.setState({ pagestart: e, start,ischeckbox:!1 }, () => {
//             this.freshlist(start,state)
//         })
//     }
    setpage(e){
        let {pagesize,start}=this.state
        pagesize=parseInt(e)
        start=0
        this.setState({pagesize,start},()=>{
            this.freshlist(start)
        })
    }
    setpager(pagecount, start) {
        let counts = [];
        for (let i = 1; i < pagecount + 1; i++) {
            counts.push(start + i)
        }
        this.setState({ counts })
    }
    clickpage(e) {
        console.log(e)
        let { start, pagesize } = this.state
        start = e * pagesize
        this.setState({ pagestart: e, start }, () => {
            this.freshlist(start)
        })
    }
    // 图片
    filechangeimg(e) {
        var that = this;
        var filedata = $('#file' + e)[0].files[0];
        let _name, _fileName;
        _name = $('#file' + e)[0].value;
        _fileName = _name.substring(_name.lastIndexOf(".") + 1).toLowerCase();
        if (_fileName !== "png" && _fileName !== "jpg" && _fileName !== "gif" && _fileName !== "jpeg") {
            alert("上传图片格式不正确，请重新上传");
        } else {
            if (e == '3') {
                this.setState({
                    fileimgshow: !1,
                    imgstate: ''
                })
            }
            else if (e == '1') {
                this.setState({
                    lbfileimgshow: !1,
                    lbimgstate: ''
                })
            }
            let filee = e
            var reader = new FileReader();
            reader.readAsDataURL(filedata);
            reader.onload = function (e) {
                var base64str = e.target.result;
                that.putswiperimglistdata([base64str], filee)
            }
        }
    }
    putswiperimglistdata(target, e) {
        let { imgsrc } = this.state;
        if (e == '3') {
            imgsrc = target[0]
            if (!isBase64(imgsrc)) {
                if (imgsrc.indexOf(`${API_HEAD}`) == -1) {
                    imgsrc = `${API_HEAD}imgs/${src}`

                }
            }
        }

        this.setState({
            imgsrc
        })

    }
    clickupload(e) {
        $('#file' + e).click();
    }
    del_img(e) {
        if (e == '3') {
            this.setState({
                imgsrc: '',
                fileimgshow: !0,
                imgstate: '',
            })
        }
    }
    // 上传图片
    uploadimg(arr) {
        let uploadimgarr = [], { name, namber,imgsrc,start } = this.state,that=this
        arr.forEach((x, i) => {
            if (x.indexOf(`${API_HEAD}`) == -1) {
                if (isBase64(x)) {
                    uploadimg(x, res => {
                        if (res.issuccess == 1) {
                            x = `${API_HEAD}imgs/${res.path}`
                            uploadimgarr.push(x)
                        } else {
                            alert(res.msg)
                            err = 1
                            return;
                        }
                    })
                }
            } else {
                uploadimgarr.push(x)
            }
        })
        if (uploadimgarr.length == arr.length) {
            uploadimgarr.forEach((x, i) => {
                imgsrc = x.replace(`${API_HEAD}imgs/`, '')
            })

            var data = { name, orders: namber,thumbpath:imgsrc }
    
            if (this.state.id > 0) data['id'] = this.state.id;
            audiocateaoe(data, res => {
                if (res.issuccess == 1) {
                    alert(`${this.state.id > 0 ? '修改' : '保存'}成功`);
                    that.setState({id: 0, fileimgshow: !0, imgsrc: '', name: ''})
                    that.freshlist(start)
                }
            })
        }
    }
    add(){
        that.setState({id: 0, fileimgshow: !0, imgsrc: '', name: ''})
    }
    render() {
        let { clicknew, counts, listitem, pagestart, keyword, imgsrc, name, namber,wulist } = this.state;

        return (
            <div className="breadLinebox">
                <Modal content='确定要删除吗？' click={this.confirmdel.bind(this)} />
                    <div className="modal fade" id="modalOne" >
                        <div className="modal-dialog">
                            <div className="modal-content">

                            <div className="modal-header border">
                                <p className="modal-title">{this.state.id>0?"编辑":"新建"}</p>
                                <img data-dismiss="modal" src="./src/close.png"/>
                                        </div>
                            <div className="modal-body">
                            <div className="input-group">
                                    <span className="input-group-addon">分类名称</span>
                                    <input id='name' onChange={this.inputchange.bind(this,'name')} value={name} type="text" placeholder='请输入分类名称' className="input" />
                                </div>
                                <div className="input-group">
                                    <span className="label input-group-addon">分类图片</span>
                                    <input onChange={this.filechangeimg.bind(this, '3')} type='file' id='file3' style={{ display: "none" }} />
                                    <div className='detail_btns'>
                                        <img className='fileimg' src={Constant.UPLOADBTN} onClick={this.clickupload.bind(this, '3')} style={{ display: this.state.fileimgshow ? "" : "none" }} />
                                        <div className="img_warp" style={{ display: this.state.fileimgshow ? "none" : "" }}>
                                            <img src={imgsrc} className="img" />
                                            <img className='closeimg' onClick={this.del_img.bind(this, '3')} src='./src/img_close.png' style={{ display: this.state.fileimgshow ? "none" : "" }} />
                                        </div>
                                    </div>
                                    {/* <span className="proposal">建议上传80*80的图片</span> */}
                                </div>
                                <div className="input-group">
                                    <span className="input-group-addon">排序</span>
                                    <input id='name' onChange={this.inputchange.bind(this,'namber')} value={namber} type="text" placeholder='请输入0-100的数字' className="input" />
                                </div>
                            {/* <div className="input-group">
                                    <span className="">音频名称</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'name')} value={target.name} type="text" placeholder='请输入分类名称' className="input" />
                                </div>
                                <div className="input-group">
                                    <span className="">排序</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'namber')} value={target.namber} type="text" placeholder='请输入0-100的数字' className="sorts" />
                                </div> */}
                            </div>
                            <div className="modal-footer border">
                                <button type="button" className="closemod" data-dismiss="modal">关闭</button>
                                <button type="button" onClick={this.submit.bind(this)} data-dismiss="modal"  className="submitmod">提交</button>
                            </div>

                            </div>
                            </div>
                        </div>





                <div className='content_wrap panel-default content_wrap'>

                    <div className='breadLine '>
                        当前位置 > 音频分类管理
                     </div>
                     
                    <div className="content">
                        <div className="tabletit" >
                        <p className="add" data-toggle="modal" data-target="#modalOne" onClick={this.add.bind(this)}>新建</p>
                        
                            {/* <p className="add" data-toggle="modal" data-target="#modalOne" onClick={this.getnew.bind(this)} >{this.state.id == 0 ? "新建" : "编辑"}名称</p> */}
                        </div>
                        <table className="tab">
                            <thead>
                                <tr>

                                    <th>音频图片</th>
                                    <th>音频名称</th>
                                    <th className="tconter">状态</th>
                                    <th className="tconter">排序</th>
                                    <th className="cz tconter">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {listitem}
                            </tbody>
                        </table>
                        {wulist}
                    </div>








                    <div className="pagerbox">
                            <p>共{this.state.total}条</p>
                            <Pager counts={counts} click={this.clickpage.bind(this)} change={this.setpage.bind(this)} index={pagestart} />
                        </div>


                </div>

            </div>


        )


    }
}





ReactDOM.render(
    <div>
        <TopLine />
        <div id='body'>
            <LeftMenu code='audiomanagement' />
            <Main />
        </div>
    </div>
    // <Barrage/>
    , $('.container')[0]
)
